﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdverseEventReportSystem.Utils {
	public static class TreeHelper {
		#region 根据DataTable获取JsonTree
		/// <summary>
		/// 根据DataTable获取下拉列表
		/// </summary>
		/// <param name="dt">DataTable数据源</param>
		/// <param name="idFieldName">ID字段名称</param>
		/// <param name="textFieldName">text字段名称</param>
		/// <param name="parentIDFieldName">父级ID字段名称</param>
		/// <param name="attrFieldName">attr字段名称</param>
		/// <returns></returns>
		public static List<TreeItem> GetList(DataTable dt, string idFieldName, string textFieldName, string parentIDFieldName, string attrFieldName, string parentID = "0") {
			List<TreeItem> list = new List<TreeItem>();
			DataRow[] arrDr = dt.Select(parentIDFieldName + "='" + parentID + "'");
			foreach (var dr in arrDr) {
				TreeItem item = new TreeItem();
				item.ID = dr[idFieldName].ToString();
				item.Text = dr[textFieldName].ToString();
				item.ParentID = dr[parentIDFieldName].ToString();
				item.Attr = dr[attrFieldName].ToString();
				#region 可选参数
				try {
					item.IsChecked = DataConvert.StrToInt(dr["IsChecked"]);
				}
				catch { }
				try {
					item.IsEnable = DataConvert.StrToInt(dr["IsEnable"]);
				}
				catch { }
				try {
					item.Seq = DataConvert.StrToInt(dr["Seq"]);
				}
				catch { }
				#endregion
				item.children = GetChildList(dt, idFieldName, textFieldName, parentIDFieldName, attrFieldName, item.ID); ;
				list.Add(item);
			}
			return list;
		}

		private static List<TreeItem> GetChildList(DataTable dt, string idFieldName, string textFieldName, string parentIDFieldName, string attrFieldName, string parentID) {
			List<TreeItem> list = new List<TreeItem>();
			DataRow[] arrDr = dt.Select(parentIDFieldName + "='" + parentID + "'");
			foreach (DataRow dr in arrDr) {
				TreeItem item = new TreeItem();
				item.ID = dr[idFieldName].ToString();
				item.Text = dr[textFieldName].ToString();
				item.ParentID = dr[parentIDFieldName].ToString();
				item.Attr = dr[attrFieldName].ToString();
				#region 可选参数
				try {
					item.IsChecked = DataConvert.StrToInt(dr["IsChecked"]);
				}
				catch { }
				try {
					item.IsEnable = DataConvert.StrToInt(dr["IsEnable"]);
				}
				catch { }
				try {
					item.Seq = DataConvert.StrToInt(dr["Seq"]);
				}
				catch { }
				#endregion
				item.children = GetChildList(dt, idFieldName, textFieldName, parentIDFieldName, attrFieldName, item.ID); ;
				list.Add(item);
			}
			return list;
		}
		#endregion
	}
}
